class OnObj {
  constructor(name, cb, key) {
    this.name = name;
    this.cb = cb;
    this.key = key;
  }
}

class EventBus {
  constructor() {}
  key = 0;

  msgList = {};

  on(msgName, fn) {
    let obj = {
      cb: fn,
      key: this.key++,
    };
    if (!this.msgList.hasOwnProperty(msgName)) {
      this.msgList[msgName] = [obj];
    } else {
      this.msgList[msgName].push(obj);
    }
    return new OnObj(msgName, fn, obj.key);
  }

  emit(msgName, data) {
    if (this.msgList.hasOwnProperty(msgName)) {
      this.msgList[msgName].map((obj) => obj.cb(data));
    }
  }

  off(obj) {
    if (obj instanceof OnObj) {
      this.msgList[obj.name] = this.msgList[obj.name].filter((v) => {
        return v.key !== obj.key;
      });
      console.log(this.msgList[obj.name].length);
      if (!this.msgList[obj.name].length) {
        delete this.msgList[obj.name];
      }
    }
  }
}

const eventBus = new EventBus();

const test = eventBus.on("test", (data) => {
  console.log(data);
});
eventBus.on("test", (data) => {
  console.log(data, "111");
});

eventBus.off(test);

eventBus.emit("test", "aaa");
